<template>
    <div>
        <div v-if="addType === '0'">
            <el-form
                ref="paperPropsForm"
                :model="paperPropsForm"
                :inline="true"
                :rules="paperRules"
                label-width="10em"
                class="data-form"
            >
                <div class="form-item xy-start al-str">
                    <div v-show="isShowBtn" class="childrenDiv">
                        <el-form-item>
                            <el-button
                                type="primary"
                                @click="paperComplete('paperPropsForm')"
                            >{{ saveName }}
                            </el-button
                            >
                            <el-button
                                type="primary"
                                @click="uploadPaper"
                            >上传试卷
                            </el-button
                            >
                            <!--                        <el-button @click="resetForm('paperForm')">重置试卷</el-button>-->
                        </el-form-item>
                    </div>
                    <div class="title">
                        {{
                            isShowBtn
                                ? addType === "0"
                                    ? "填写试卷信息"
                                    : "选择章节"
                                : addType === "0"
                                    ? "试卷信息"
                                    : "章节信息"
                        }}
                    </div>
                    <div class="" align="">
                        <div
                            v-show="isShowBtn && addStyleBtn"
                            class="childrenDiv"
                        >
                            <el-radio-group v-model="addType">
                                <el-radio label="0" border>添加到试卷</el-radio>
                                <el-radio label="1" border>添加到章节</el-radio>
                            </el-radio-group>
                        </div>
                        <div class="childrenDiv">
                            <el-form-item label="所属科目" prop="categoryId">
                                <category-select
                                    :is-disabled="saveName === '编辑完成'"
                                    :category-id.sync="
                                        paperPropsForm.categoryId
                                    "
                                    :props="{}"
                                />
                            </el-form-item>
                        </div>
                        <!-- <div class="childrenDiv">
                            <el-form-item
                                label="所属栏目"
                                prop="columnId">
                                <el-select v-model="paperPropsForm.columnId" clearable placeholder="请选择">
                                    <el-option
                                        v-for="item in columns"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </div> -->
                        <div class="childrenDiv">
                            <el-form-item label="试卷类型" prop="paperType">
                                <el-select
                                    v-model="paperPropsForm.paperType"
                                    clearable
                                    placeholder="请选择"
                                >
                                    <el-option
                                        v-for="k in Object.keys(paperType)"
                                        :key="k"
                                        :label="paperType[k].desc"
                                        :value="k"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </div>
                        <div class="childrenDiv">
                            <el-form-item label="所属年份" prop="sourceYear">
                                <el-date-picker
                                    v-model="paperPropsForm.sourceYear"
                                    type="year"
                                    value-format="yyyy"
                                    placeholder="选择年份"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </div>
                        <div class="childrenDiv">
                            <el-form-item label="试卷时长" prop="examTime">
                                <el-input
                                    v-model.number="paperPropsForm.examTime"
                                    clearable
                                    placeholder="试卷时长"
                                ></el-input>
                            </el-form-item>
                        </div>
                        <div class="childrenDiv">
                            <el-form-item label="试卷总分" prop="totalScore">
                                <el-input
                                    v-model.number="paperPropsForm.totalScore"
                                    clearable
                                    placeholder="试卷总分"
                                ></el-input>
                            </el-form-item>
                        </div>
                        <div class="childrenDiv">
                            <el-form-item label="试卷及格分" prop="passScore">
                                <el-input
                                    v-model.number="paperPropsForm.passScore"
                                    clearable
                                    placeholder="试卷及格分"
                                ></el-input>
                            </el-form-item>
                        </div>
                        <div class="childrenDiv">
                            <el-form-item label="试卷名称" prop="name">
                                <el-input
                                    v-model="paperPropsForm.name"
                                    clearable
                                    placeholder="试卷名称"
                                ></el-input>
                            </el-form-item>
                        </div>
                        <div class="childrenDiv">
                            <el-form-item label="试卷排序" prop="sort">
                                <el-input
                                    v-model.number="paperPropsForm.sort"
                                ></el-input>
                            </el-form-item>
                        </div>
                        <div class="childrenDiv">
                            <el-form-item label="试卷描述" prop="remark">
                                <el-input
                                    v-model="paperPropsForm.remark"
                                    type="textarea"
                                ></el-input>
                            </el-form-item>
                        </div>
                        <div class="childrenDiv">
                            <el-form-item label="请选择word">
                                <el-upload ref="uploadFile" action="" :auto-upload="false" :http-request="customUpload" :limit="1">
                                    <i class="el-icon-plus"></i>
                                </el-upload>
                            </el-form-item>
                        </div>
                    </div>
                </div>
            </el-form>
        </div>
        <div v-else>
            <el-form
                ref="paperPropsForm"
                :model="chapterPropsForm"
                :inline="true"
                :rules="chapterRules"
                label-width="10em"
                class="data-form"
            >
                <div class="form-item xy-start al-str">
                    <div v-show="isShowBtn" class="childrenDiv">
                        <el-form-item>
                            <el-button
                                type="primary"
                                @click="paperComplete('chapterPropsForm')"
                            >{{ saveName }}
                            </el-button
                            >
                            <el-button
                                type="primary"
                                @click="uploadPaper"
                            >上传试卷
                            </el-button
                            >
                        </el-form-item>
                    </div>
                    <div class="title">
                        {{
                            isShowBtn
                                ? addType === "0"
                                    ? "填写试卷信息"
                                    : "选择章节"
                                : addType === "0"
                                    ? "试卷信息"
                                    : "章节信息"
                        }}
                    </div>
                    <div class="" align="">
                        <div
                            v-show="isShowBtn && addStyleBtn"
                            class="childrenDiv"
                        >
                            <el-radio-group v-model="addType">
                                <el-radio label="0" border>添加到试卷</el-radio>
                                <el-radio label="1" border>添加到章节</el-radio>
                            </el-radio-group>
                        </div>
                        <div class="childrenDiv">
                            <el-form-item label="请选择学科" prop="categoryId">
                                <category-select
                                    :category-id.sync="
                                        chapterPropsForm.categoryId
                                    "
                                    :props="{}"
                                />
                            </el-form-item>
                        </div>
                        <div class="childrenDiv">
                            <el-form-item label="请选择章节" prop="chapterId">
                                <chapter-select
                                    :category-id="categoryId"
                                    :chapter-id.sync="
                                        chapterPropsForm.chapterId
                                    "
                                    :props="{}"
                                />
                            </el-form-item>
                        </div>
                        <div class="childrenDiv">
                            <el-form-item label="请选择word">
                                <el-upload ref="uploadFile1" action="" :auto-upload="false" :http-request="customUpload" :limit="1">
                                    <i class="el-icon-plus"></i>
                                </el-upload>
                            </el-form-item>
                        </div>
                    </div>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script>
import {questionComponents} from "@/views/models/exam/questionBase/question/mixins/question";
import CategorySelect from "@/components/CategorySelect";
import {post, put} from "@/api/request";
import ChapterSelect from "@/components/ChapterSelect";
import {fetchChapterById, fetchColumnList, fetchQuestionType} from "@/api/exam";
import {mapState} from "vuex";

export default {
    name: "AddPaperBox",
    components: {CategorySelect, ChapterSelect},
    mixins: [questionComponents],
    props: {
        paperPropsForm: {
            type: Object,
            default: () => []
        },
        chapterPropsForm: {
            type: Object,
            default: () => []
        },
        saveName: {
            type: String,
            default: "完成保存"
        },
        isShowBtn: {
            type: Boolean,
            default: true
        },
        addStyleBtn: {
            type: Boolean,
            default: true
        }
    },
    data() {
        return {
            isChapter: false,
            categoryId: null,
            chapterForms: {},
            addType: "0", // 试题添加到章节或试卷
            columns: []
        };
    },
    computed: {
        ...mapState({
            paperType: state => state.status.paperType
        })
    },
    watch: {
        "chapterPropsForm.categoryId"(ne, id) {
            this.categoryId = ne;
            if (id !== undefined) {
                this.chapterPropsForm.chapterId = null;
                this.$emit("clear-question-box-f");
            }
        },
        "chapterPropsForm.chapterId"(id) {
            if (id !== null && id !== undefined) {
                this.$emit("clear-question-box-f");
                this.getChapterQuestion(id);
            }
        },
        "paperPropsForm.categoryId"(id) {
            fetchColumnList({categoryId: id, type: "paperLibrary"}).then(
                res => {
                    this.columns = res;
                    if (this.isShowBtn && this.paperPropsForm.id === null) {
                        this.paperPropsForm.columnId = "";
                    }
                }
            );
        },
        addType(vl) {
            this.$emit("addStyleContent", vl);
        }
    },
    methods: {
        // 完成保存
        paperComplete(formName) {
            // 保存到试卷
            if (this.addType === "0") {
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        if (
                            this.paperPropsForm.content !== null &&
                            this.paperPropsForm.content.length > 0
                        ) {
                            let totalScore = 0;
                            this.paperPropsForm.content.forEach(v => {
                                let bScore = v.score;
                                totalScore += bScore;
                            });
                            if (totalScore > this.paperPropsForm.totalScore) {
                                return this.$message({
                                    message:
                                        "试卷总分应该大于等于大题型分数相加",
                                    type: "error"
                                });
                            }
                        }
                        if (this.paperPropsForm.id !== null) {
                            put("exam/paper/update", this.paperPropsForm).then(
                                data => {
                                    if (data) {
                                        this.$message({
                                            message: "恭喜你，试卷编辑成功",
                                            type: "success"
                                        });
                                    }
                                }
                            );
                        } else {
                            this.$confirm(
                                "确定保存试卷，保存后页面内容信息将清空, 是否继续?",
                                "提示",
                                {
                                    confirmButtonText: "确定",
                                    cancelButtonText: "取消",
                                    type: "warning"
                                }
                            )
                                .then(() => {
                                    post(
                                        "exam/paper/update",
                                        this.paperPropsForm
                                    ).then(data => {
                                        if (data) {
                                            this.$message({
                                                message:
                                                    "恭喜你，试卷保存成功，请继续添加试题试卷",
                                                type: "success"
                                            });
                                            this.$emit("clear-question-box-f");
                                        }
                                    });
                                })
                                .catch(() => {
                                    this.$message({
                                        type: "info",
                                        message: "已取消"
                                    });
                                });
                        }
                        // 保存到后端
                    } else {
                        console.log("error submit!!");
                        return false;
                    }
                });
            } else {
                // 保存到章节
                this.chapterForms.content = this.chapterPropsForm.content;
                if (
                    this.chapterPropsForm.chapterId === null ||
                    this.chapterPropsForm.chapterId === undefined
                ) {
                    return this.$message.error("错了哦，请选择章节添加试题！");
                }
                put("exam/chapter/update", this.chapterForms).then(data => {
                    if (data) {
                        this.$message({
                            message: "恭喜你，章节保存成功",
                            type: "success"
                        });
                    }
                });
            }
        },
        getChapterQuestion(val) {

            fetchChapterById({id: val}).then(res => {
                this.chapterForms = res;
                this.$emit("questionContent", res);
            });
        },
        uploadPaper() {
            if(this.addType=="0"){
                this.$refs.uploadFile.submit();
            }else{
                this.$refs.uploadFile1.submit();
            }

//             let obj={
//                 id:"",
//                 "free",
//                 "columnId",
//                 "categoryId",
//                 "knowledgeLevel",
//                 "name",
//             serverName
//                 "parentId",
//                 "path",
//                 "leaf",
//                 "sort",
//                 "remark",
//                 "qcount"
//             }
        },
        customUpload(options) {
            if(this.addType=="0"){
                const formData = new FormData();
                formData.append("file", options.file);
                formData.append("paper", JSON.stringify({
                    ...this.paperPropsForm, knowledgeLevel: 5,
                }));
                post("exam/paper/addPaperWithFile", formData, "").then(res=>{
                    this.$message.success("上传成功");
                })
            }else{
                const formData = new FormData();
                formData.append("file", options.file);
                let requestObj=JSON.parse(JSON.stringify(this.chapterForms))

                formData.append("params", JSON.stringify({...requestObj, knowledgeLevel: 5,}));

                put("exam/chapter/updateWithFile", formData).then(res=>{
                    this.$message.success("上传成功");
                })
            }
        }
    }
};

// /exam/paper/detail  在响应的content属性里有所有实体
// SELECT * FROM ex_question_expand WHERE deleted=0 AND (sign = 'abd9026fa480f517bfe74bd058c054d4')
// var a=[
// {
//     "id": "162_1906641964086853632",
//     "sort": 5,
//     "score": 1
// },
// {
//     "id": "162_1906641964086853633",
//     "sort": 2,
//     "score": 1
// },
// {
//     "id": "162_1906641964086853634",
//     "sort": 3,
//     "score": 1
// },
// {
//     "id": "162_1906641964086853635",
//     "sort": 4,
//     "score": 1
// },
// {
//     "id": "162_1906641964086853636",
//     "sort": 1,
//     "score": 1
// },
// {
//     "id": "162_1906641964086853637",
//     "sort": 6,
//     "score": 1
// }
// ]

</script>

<style lang="scss" scoped>
.childrenDiv {
    margin-top: 6px;
}
</style>
